import router from "./router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { isHttp } from "@/utils/validate";
import usePermissionStore from "@/store/modules/permission";
NProgress.configure({ showSpinner: false });
let routerOk = false
router.beforeEach((to, from, next) => {
	NProgress.start();
	if (to.path === "/login") {
		next();
		NProgress.done();
	} else {
		if (sessionStorage.getItem("userName")) {
			if (!routerOk) {
				usePermissionStore()
					.generateRoutes()
					.then((accessRoutes) => {
						// 根据roles权限生成可访问的路由表
						accessRoutes.forEach((route) => {
							if (!isHttp(route.path)) {
								router.addRoute(route); // 动态添加可访问路由表
							}
						});
						routerOk = true
						next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
					});
			} else {
				next();
			}
		} else {
			next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
			NProgress.done();
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
